package com.example.demospringsecurity.Service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.demospringsecurity.Service.LoginService;
import com.example.demospringsecurity.domain.LoginUser;
import com.example.demospringsecurity.domain.ResponseResult;
import com.example.demospringsecurity.domain.User;
import com.example.demospringsecurity.filter.JwtAuthenticationTokenFilter;
import com.example.demospringsecurity.mapper.MenuMapper;
import com.example.demospringsecurity.mapper.UserMapper;
import com.example.demospringsecurity.util.JwtUtil;
import com.example.demospringsecurity.util.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Objects;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private RedisCache redisCache;

    @Override
    public ResponseResult login(User user) {
        //AuthenticationManager的authenticate方法来进行用户认证
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());
        //用户认证走loadByusername方法
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);

        //如果认证没通过，给出对应的提示
        if (Objects.isNull(authenticate)) {
            throw new RuntimeException("登录失败");
        }

        //如果认证通过了，使用userid生成jwt，使用jwt生成token，返回token
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String userId = loginUser.getUser().getId().toString();
        String jwt = JwtUtil.createJWT(userId);


        HashMap<String, String> map = new HashMap<>();
        map.put("token", jwt);
        //把完整的用户信息存入redis
        redisCache.setCacheObject("login:" + userId, loginUser);
        return new ResponseResult(200, "登录成功", map);
    }

    //方式二，不走loadByUsername
//    @Autowired
//    private UserMapper userMapper;
//    @Autowired
//    private MenuMapper menuMapper;
//    @Override
//    public ResponseResult login(User user) {
//        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
//        wrapper.eq(User::getUserName,user.getUserName());
//        User userInfo = userMapper.selectOne(wrapper);
//        //如果查询不到数据就通过抛出异常来给出提示
//        if(Objects.isNull(userInfo)){
//            throw new RuntimeException("用户名或密码错误");
//        }
//        List<String> list = menuMapper.selectPermsByUserId(userInfo.getId());
//        LoginUser loginUser = new LoginUser(userInfo, list);
//
//        String userId = loginUser.getUser().getId().toString();
//        String jwt = JwtUtil.createJWT(userId);
//
//
//        HashMap<String, String> map = new HashMap<>();
//        map.put("token", jwt);
//        //把完整的用户信息存入redis
//        redisCache.setCacheObject("login:" + userId, loginUser);
//        return new ResponseResult(200, "登录成功", map);
//    }

    @Override
    public ResponseResult logout() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        Long userid = loginUser.getUser().getId();
        redisCache.deleteObject("login:" + userid);
        return new ResponseResult(200, "退出成功");
    }
}
